package com.lam.framework.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.MDC;

import com.lam.common.context.ContextHolder;
import com.lam.common.context.TokenUtils;
import com.lam.common.utils.StringUtils;

public class LogMDCFilter implements Filter {
	
	private final String requestIdKey = "reqTrace";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    	
    	String username = TokenUtils.getLoginUsername();
        if(StringUtils.isBlank(username)) {
        	username = "anonymous";
        }
        String requestTrace = String.format("reqid:%s-%s", ContextHolder.getTraceId(), username);
        MDC.put(requestIdKey, requestTrace);
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            MDC.remove(requestIdKey);
        }
    }

    @Override
    public void destroy() {

    }
}
